package com.financing.wap.web.controller.api;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.CommonConstantUtil.CommonStatus;
import com.financing.wap.dto.DstPosterDTO;
import com.financing.wap.dto.DstUserInfoDTO;
import com.financing.wap.dto.DstUserInfoExpandDTO;
import com.financing.wap.service.IDstPosterService;
import com.financing.wap.service.IDstUserInfoExpandService;
import com.financing.wap.service.IDstUserInfoService;
import com.financing.wap.util.AliyunOssUtil;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;
/***
 *海报
 */
@Controller("dstPosterController")
@RequestMapping("/api/dstPoster")
public class DstPosterController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IDstPosterService dstPosterService;
	
	@Autowired
	private IDstUserInfoExpandService dstUserInfoExpandService;
	
	@Autowired
	private IDstUserInfoService dstUserInfoService;

	// 保存文件到本地目录
	private static String ossUserCardPath = PropertiesUtils.getValue("ossUserCardPath");
	
	@RequestMapping("/listDstPoster")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, DstPosterDTO dstPoster,Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query dstPoster list begin .......");
			
			dstPoster.setBegin(pager.getStartIndex());
			dstPoster.setPageSize(pager.getPageSize());
			//上架
			dstPoster.setPosterStatus("1");
			dstPoster.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			int count = dstPosterService.queryListCount(dstPoster);
			
			pager.setTotalCount(count);
			
			List<DstPosterDTO> dstPosterList = null;
			
			TreeMap<String,List<DstPosterDTO>> map=new TreeMap<String,List<DstPosterDTO>>();
					
			if(count > 0){
				dstPosterList = dstPosterService.queryList(dstPoster);
				for (int i = dstPosterList.size()-1; i >=0 ; i--) {
					DstPosterDTO dto = dstPosterList.get(i);
					String posterDate = dto.getPosterDate();
					String dd = (DateUtil.format(posterDate, "yyyy-MM-dd").getMonth()+1)+"";
					
					if(map.containsKey(dd)){
						map.get(dd).add(dto);
					}else{
						List<DstPosterDTO> dt=new ArrayList<DstPosterDTO>();
						dt.add(dto);
						map.put(dd, dt);
					}
				}
			}
			result.setAttribute("pager", pager);
			result.setAttribute("map", JSONObject.toJSONString(map.descendingMap()));
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query dstPoster list end .......");
		}catch(Exception e){
			log.error("query dstPoster error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	/***
	 * 生成用户二维码海报合成
	 */
	@RequestMapping("/posterMarkLogo")
	@ResponseBody
	public ResultMap posterMarkLogo(HttpServletRequest request){
		ResultMap result = new ResultMap();
		try{
			logger.info("posterMarkLogoMark  begin .......");
			String openid = request.getParameter("openid");
			String posterId = request.getParameter("posterId");
			if(StringUtil.isNullOrEmptyStr(openid,posterId)){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			DstPosterDTO dto = dstPosterService.loadById(Integer.parseInt(posterId));
			String posterImageUrl = dto.getPosterImageUrl();
			DstUserInfoExpandDTO dstUserInfoExpand=new DstUserInfoExpandDTO();
			dstUserInfoExpand.setUserOpenid(openid);
			DstUserInfoExpandDTO expand = dstUserInfoExpandService.queryListGetFirst(dstUserInfoExpand);
			String userCardImg = expand.getUserCardImg();
			
			DstUserInfoDTO dstUserInfo = new DstUserInfoDTO();
			dstUserInfo.setUserWechatOpenid(openid);
			dstUserInfo.setDeleteTag(CommonStatus.DELETE_TAG_NORMAL);
			DstUserInfoDTO userinfo = dstUserInfoService
					.queryListGetFirst(dstUserInfo);
			if(userinfo.getId()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			if(StringUtils.isNotBlank(userCardImg)&&StringUtils.isNotBlank(posterImageUrl)){
		        //目录
		        StringBuffer fileFull = new StringBuffer();
		        fileFull.append(ossUserCardPath)
		                .append("/").append("userPosterImage").append("/")
		                .append(DateUtil.formatDate(userinfo.getCreateDate(), "yyyyMMdd")).append("/")
		                .append(openid).append("_").append(posterId).append(".jpg");
		        result.setAttribute("imageUrl",CommonConstantUtil.OSS_PATH+fileFull.toString());
//				if(AliyunOssUtil.doesObjectExist(fileFull.toString())){
//					result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
//					result.setStatus(ResultMap.STATUS.SUCCESS);
//					return result;
//				}
		        String tempPath="/disk/upload/watertemp/"+openid+posterId+".jpg";
		        AliyunOssUtil.markPoster(posterImageUrl.replace(CommonConstantUtil.OSS_PATH, ""), userCardImg.replace(CommonConstantUtil.OSS_PATH, ""), tempPath,fileFull.toString());
			}else{//二维码为空   返回海报地址
				result.setAttribute("imageUrl",posterImageUrl);
			}
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			logger.info("posterMarkLogo end .......");
		}catch(Exception e){
			log.error("posterMarkLogo error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
}
